import React, { Component } from 'react';
import { Form, Input, Modal, Popover, Icon } from 'antd';
import { formatMessage } from 'umi/locale';
import Des from '@/utils/des';
import styles from './index.less';
import { connect } from 'dva';
const FormItem = Form.Item;

@connect()
@Form.create()
class Password extends Component {
  state = {
    visible: false,
    help: '',
    password: {
      length: false,
      chars: false,
      category: false,
    },
  };

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    try {
      let el = this.oldPasswordRef.current || this.oldPasswordRef;
      el.focus();
    } catch (error) {
      console.log(error);
    }
  }

  checkPassword = (rule, _value, callback) => {
    const { visible } = this.state;
    let value = _value.replace(/\s*/g, '');
    if (!value) {
      this.setState({
        help: formatMessage({ id: 'validation.password.new.required' }),
        visible: !!value,
      });
      callback('error');
    } else {
      this.setState({
        help: '',
      });
      if (!visible) {
        this.setState({
          visible: !!value,
        });
      }
      let checkPassword = () => {
        let regNumber = /\d+/; //验证0-9的任意数字最少出现1次。
        // let regCapital = /[A-Z]+/; //验证大小写26个字母任意字母最少出现1次。
        let regLowercase = /[a-zA-Z]+/; //验证大小写26个字母任意字母最少出现1次。
        let regSymbol = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im; //。
        let regCn = /[\u4e00-\u9fa5]/gm;
        let number = regNumber.test(value); // 。
        // let capital = regCapital.test(value); // 大写
        let lowercase = regLowercase.test(value); //
        let symbol = regSymbol.test(value); //
        let valueLength = (value && value.length) || 0; //
        let _n = [number, lowercase, symbol].filter(v => v).length;
        let chars = !regCn.test(value);
        this.setState({
          password: {
            length: valueLength >= 6 && valueLength <= 18,
            category: _n >= 2,
            chars,
          },
        });
        if (valueLength >= 6 && valueLength <= 18 && _n >= 2 && chars) {
          return 'pass';
        }
        return 'poor';
      };
      this.setState({
        visible: checkPassword() === 'poor',
      });
      if (checkPassword() === 'poor') {
        this.setState({
          help: '密码设置不符合要求',
          visible: true,
        });
        callback('error');
      } else {
        callback();
      }
    }
  };
  validatePassword = (rule, value, callback) => {
    const { newPassword, repeatPassword } = this.props.form.getFieldsValue();

    if (newPassword !== repeatPassword) {
      return callback(formatMessage({ id: 'validation.password.old-new-equal' }));
    }
    callback();
  };
  changePasswordSubmit = () => {
    const {
      form,
      dispatch,
      currentUser: { needResetPwd },
    } = this.props;
    form.validateFields((err, values) => {
      if (err) return;
      if (values.oldPassword && !needResetPwd)
        values.oldPassword = Des.enc(values.oldPassword);
      if (values.newPassword) values.newPassword = Des.enc(values.newPassword);
      if (values.repeatPassword) values.repeatPassword = Des.enc(values.repeatPassword);
      let payload = needResetPwd ? { pathParams: { password: values.repeatPassword } } : {
        data: {
          ...values,
        },
      }
      dispatch({
        type: needResetPwd ? 'auth/forceUpdatePassword' : 'auth/updatePassword',
        payload
      }).then(res => {
        if (res.errorCode === 0) {
          Modal.success({
            title: formatMessage({ id: 'tips.account.info.password.change.title' }),
            content: formatMessage({ id: 'tips.account.info.password.change.success' }),
          });

          const { currentUser } = this.props;
          dispatch({
            type: 'user/saveCurrentUser',
            payload: {
              ...currentUser,
              needResetPwd: false,
            },
          });
          dispatch({
            type: 'auth/logout',
          });
        }
      });
    });
  };
  render() {
    const {
      currentUser: { needResetPwd },
      form: { getFieldDecorator },
    } = this.props;
    const {
      help,
      visible,
      password: { length, chars, category },
    } = this.state;
    const formItemLayout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };

    return (
      <div className={styles.container}>
        {!needResetPwd && (
          <FormItem
            {...formItemLayout}
            label={formatMessage({ id: 'account.info.password.old-password' })}
          >
            {getFieldDecorator('oldPassword', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'validation.password.old.required' }),
                },
              ],
            })(<Input type="password" maxLength={18} ref={el => (this.oldPasswordRef = el)} />)}
          </FormItem>
        )}
        <FormItem
          {...formItemLayout}
          help={help}
          label={formatMessage({ id: 'account.info.password.new-password' })}
        >
          <Popover
            getPopupContainer={node => node.parentNode}
            content={
              <div style={{ padding: '4px 0', lineHeight: '30px' }}>
                <div>
                  {length && (
                    <Icon type="check-circle" style={{ color: '#3cb14f', marginRight: 5 }} />
                  )}
                  {!length && (
                    <Icon type="close-circle" style={{ color: '#ee563b', marginRight: 5 }} />
                  )}
                  6-18个字符，除空格
                </div>
                <div>
                  {chars && (
                    <Icon type="check-circle" style={{ color: '#3cb14f', marginRight: 5 }} />
                  )}
                  {!chars && (
                    <Icon type="close-circle" style={{ color: '#ee563b', marginRight: 5 }} />
                  )}
                  只能包含字母、数字以及标点符号
                </div>
                <div>
                  {category && (
                    <Icon type="check-circle" style={{ color: '#3cb14f', marginRight: 5 }} />
                  )}
                  {!category && (
                    <Icon type="close-circle" style={{ color: '#ee563b', marginRight: 5 }} />
                  )}
                  字母、数字、符号至少包含两种
                </div>
              </div>
            }
            overlayStyle={{ width: 300 }}
            placement="right"
            visible={visible}
          >
            {getFieldDecorator('newPassword', {
              normalize: (value, prevValue) => {
                return value && value.replace(/\s*/g, '');
              },
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'validation.password.new.required' }),
                },
                {
                  validator: this.checkPassword,
                },
              ],
            })(
              <Input
                type="password"
                onFocus={() => {
                  this.setState({ visible: true });
                }}
                onBlur={() => {
                  this.setState({ visible: false });
                }}
                maxLength={18}
              />
            )}
          </Popover>
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={formatMessage({ id: 'account.info.password.repeat-new-password' })}
        >
          {getFieldDecorator('repeatPassword', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'validation.password.new.confirm.required' }),
              },
              { validator: this.validatePassword },
            ],
          })(<Input type="password" maxLength={18} />)}
        </FormItem>
      </div>
    );
  }
}
export default Password;
